package com.sean.common.databases;

import com.sean.framework.databases.AppDBHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DaoHelper {
	
	public static final String TAG = "DaoHelper";

	private AppDBHelper mDBHelper;
	protected SQLiteDatabase mDatabase;
	
	public DaoHelper(Context context) {
		mDBHelper = AppDBHelper.getInstance(context);
	}
	
	/**
	 * 如果插入成功，则返回插入的ID，如果失败，则返回-1
	 */
	public long save(Object obj) {
		mDatabase = mDBHelper.getReadableDatabase();
		ContentValues cv = SQLUtil.beanToContentValues(obj);
		String tableName = SQLUtil.getTableName(obj.getClass());
		long id = mDatabase.insert(tableName, null, cv);
		mDatabase.close();
		if(id != -1) {
			Log.d(TAG, "Insert a record to the table : " + tableName + " >> id = " + id);
		} else {
			Log.w(TAG, "Can't insert a record to the table : " + tableName + " >> id = " + id);
		}
		return id;
	}
	
	public boolean delete(Object obj) {
		String id = SQLUtil.getIdByBean(obj);
		return delete(obj.getClass(), id);
	}
	
	public boolean delete(Class<?> cla, long id) {
		return delete(cla, String.valueOf(id));
	}
	
	public boolean delete(Class<?> cla, String id) {
		String tableName = SQLUtil.getTableName(cla);
		mDatabase = mDBHelper.getWritableDatabase();
		int count = mDatabase.delete(tableName, "id=?", new String[]{id});
		mDatabase.close();
		if(count > 0) {
			Log.d(TAG, "Delete a record from the table : " + tableName + " >> id = " + id);
			return true;
		} else {
			Log.w(TAG, "Fail to delete a record from the table : " + tableName + " >> id = " + id);
			return false;
		}
	}
	
	public Object get(Class<?> cla, long id) {
		return get(cla, String.valueOf(id));
	}
	
	public Object get(Class<?> cla, String id) {
		String tableName = SQLUtil.getTableName(cla);
		try {
			Object obj = cla.newInstance();
			mDatabase = mDBHelper.getReadableDatabase();
			Cursor cursor = mDatabase.query(tableName, null, "id=?", new String[]{id}, null, null, null);
			if(SQLUtil.cursorToBean(cursor, obj)) {
				Log.d(TAG, "Get a record from the table : " + tableName);
				return obj;
			}
			mDatabase.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.w(TAG, "Fail to get a record from the table : " + tableName);
		return null;
	}
	
	public void close() {
		if(mDatabase != null && mDatabase.isOpen())
			mDatabase.close();
	}
	
}
